const Router = require('@koa/router');
const config = require('../../config/index');
const { validateTicket } = require('../service/app');
const { notifyClearSession, clearUserSession } = require('../service/session');

const router = new Router();

module.exports = router;

router.get('/', async (ctx, next) => {
  const { user } = ctx.session;
  const appName = process.env.appName || 'app1';

  const { ticket } = ctx.query;

  if (ticket) {
    const ticketRes = await validateTicket(ticket);
    if (ticketRes.error === 1) {
      ctx.body = ticketRes;
      return;
    }

    ctx.session.user = ticketRes.user;
    ctx.redirect('/');
    return;
  }

  if (!user || !user.id) {
    const ssoUrl = `http://${config.sso.host}:${config.sso.PORT}/auth/login`;
    const appUrl = `http://${config[appName].host}:${config[appName].PORT}/`;

    ctx.redirect(`${ssoUrl}?redirect=${appUrl}`);
    return;
  }

  await ctx.render('home', { user, appName });
  next();
});

router.get('/auth/logout', async (ctx, next) => {
  ctx.session = null;

  const uid = ctx.query.uid || ctx.session?.user?.id;
  const { ticket } = ctx.query;

  if (uid) {
    if (ticket) {
      // sso 通知当前应用清理 session
      const ticketRes = await validateTicket(ticket);
      if (ticketRes.error === 1) {
        ctx.body = ticketRes;
        return;
      }

      clearUserSession(uid);
    } else {
      // 通知全局 sso 清理 session
      await notifyClearSession(uid, 'sso');
    }
  }

  ctx.session = null;
  ctx.body = { error: 0, message: null };
  next();
});
